<?php

define('UC_AVATAR', DISCUZ_ROOT.'uc_server/data/avatar/');

function mkdirs($path, $mode = 0777) {
	$dirs = explode('/',$path);
	$pos = strrpos($path, ".");
	if ($pos === false) { // note: three equal signs
	// not found, means path ends in a dir not file
	$subamount=0;
	}
	else {
	$subamount=1;
	}
	
	for ($c=0;$c < count($dirs) - $subamount; $c++) {
		$thispath="";
		for ($cc=0; $cc <= $c; $cc++) {
		$thispath.=$dirs[$cc].'/';
		}
		if (!file_exists($thispath)) {
		//print "$thispath<br>";
		mkdir($thispath,$mode);
		}
	}
}

function get_avatar_relative_path($uid, $size = 'middle', $type = '') {
	$size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
	$uid = abs(intval($uid));
	$uid = sprintf("%09d", $uid);
	$dir1 = substr($uid, 0, 3);
	$dir2 = substr($uid, 3, 2);
	$dir3 = substr($uid, 5, 2);
	$typeadd = $type == 'real' ? '_real' : '';
	$relative = $dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2).$typeadd."_avatar_$size.jpg";
	
	return $relative;
}

function upload_avatar($uid, $url, $size='middle') {
	
	$relative = get_avatar_relative_path($uid, $size);

	$avatar_path = UC_AVATAR.$relative;
	
    $avatar_stream = fopen($url, "rb");
    
    if($avatar_stream) {
    	
        $avatar_file = fopen($avatar_path, "wb");
        
        if(!$avatar_file) {
        	
        	$dir = dirname($avatar_path);
        	
        	if(!is_dir($dir)) {
				@mkdirs($avatar_path);
			}
			
        	if(is_dir($dir)) {
        		$avatar_file = fopen($avatar_path, "wb");
        	}
        }
        
		while(!feof($avatar_stream)) {
			fwrite($avatar_file, fread($avatar_stream, 1024*8), 1024*8);
		}
		
    }
	
    if($avatar_stream) {
        fclose($avatar_stream);
    }
    if($avatar_file) {
        fclose($avatar_file);
    }
    
    return 0;
}


function rr_register($rr_uid,$dz_username) {
	define('NOROBOT', TRUE);
	loaducenter();
	global $_G;
	loadcache('plugin');
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$onlineip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$onlineip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}

	preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
	$onlineip = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
	unset($onlineipmatches);
	
	require_once libfile('class/renren_api');
	
	$api = & renren_api::instance();
	$user_info = $api->get_user_info();
	if($_G['cache']['plugin']['renren']['name']==0)
	{	$username = $user_info->name;
		$username = mb_convert_encoding($username,"GBK","UTF8");
		}
	else{$username=$dz_username;}
	$password = md5(random(20));
	$email = "$rr_uid@renren.com";
	$questionid = '';
	$answer = '';
	$uid = uc_user_register($username, $password, $email, $questionid, $answer, $onlineip);
	
	if($uid <= 0) {
			if($uid == -1) {
				showmessage('profile_username_illegal',dreferer());
			} elseif($uid == -2) {
				showmessage('profile_username_protect');
			} elseif($uid == -3) {
				if($_G['cache']['plugin']['renren']['name']==0)
				{$username = $user_info->name.$rr_uid;
				$username = mb_convert_encoding($username,"GBK","UTF8");
				$uid = uc_user_register($username, $password, $email, $questionid, $answer, $onlineip);
				if($uid<0)
					{
					showmessage('profile_username_duplicate');}
				}
				else{
					showmessage('profile_username_duplicate');
					}
			} elseif($uid == -4) {
				showmessage('profile_email_illegal');
			} elseif($uid == -5) {
				showmessage('profile_email_domain_illegal');
			} elseif($uid == -6) {
				showmessage('profile_email_duplicate');
			} else {
				showmessage('undefined_action', NULL, 'HALTED');
			}
	}
	 
	if(DB::result_first("SELECT uid FROM ".DB::table('common_member')." WHERE uid='$uid'")) {
		uc_user_delete($uid);
		showmessage('profile_uid_duplicate');
	}
	global $_G;
	loadcache('plugin');
	$groupid=intval($_G['cache']['plugin']['renren']['rr_groupid']);
	
	$userdata = array(
		'uid' => $uid,
		'username' => $username,
		'password' => $password,
		'email' => $email,
		'adminid' => 0,
		'groupid' => $groupid,
		'regdate' => TIMESTAMP,
		'timeoffset' => 9999
		);
	DB::insert('common_member', $userdata);
	DB::insert('common_member_count', array('uid' => $uid));
	rr_bind($rr_uid, $uid, 0);
	
	$status_data = array(
		'uid' => $uid,
		'regip' => $onlineip,
		'lastip' => $onlineip,
		'lastvisit' => TIMESTAMP,
		'lastactivity' => TIMESTAMP,
		'lastpost' => 0,
		'lastsendmail' => 0,
		);
	DB::insert('common_member_status', $status_data);
	
	$sex = $user_info->sex;
	$renren_profile = 'http://www.renren.com/profile.do?id='.$rr_uid;
	if(isset($sex)) {
		$sex = intval($sex) > 0 ? '1':'2';
	} else {
		$sex = '0';
	}
	
	list($birthyear, $birthmonth, $birthday) =	explode('-', $user_info->birthday);
	
	$hometown = $user_info->hometown_location;
	$birthprovince = $hometown->province;
	$city = $hometown->city;
	$company = $user_info->work_history[0]->company_name;
	$graduateschool = $user_info->university_history[0]->name;

	$birthprovince = mb_convert_encoding($birthprovince, "GBK", "UTF8");
	$city = mb_convert_encoding($city, "GBK", "UTF8");
	$company = mb_convert_encoding($company, "GBK", "UTF8");
	$graduateschool = mb_convert_encoding($graduateschool, "GBK", "UTF8");
	$username = $user_info->name;
	$username = mb_convert_encoding($username,"GBK","UTF8");
	$profile = array('uid' => $uid,
					 'realname' => $username,
					 'gender' => $sex,
					 'birthyear'=> $birthyear,
					 'birthmonth'=>$birthmonth,
					 'birthday'=>$birthday,
					 'resideprovince'=>$birthprovince,
					 'residecity'=>$city,
					 'company'=>$company,
					 'graduateschool'=>$graduateschool,
				  	 'renren' => $renren_profile);
	
	DB::insert('common_member_profile', $profile,false, true);
	$avatar = array('tinyurl'=>'', 
					'headurl'=>'', 
					'mainurl'=>'',
					'tinyurl'=>'',
					'headurl'=>'',
					'mainurl'=>'',
					);
	foreach(array_keys($avatar) as $k) {
		$avatar[$k] = $user_info->$k;
	}
	global $bbname;
	
	$welcomtitle = lang('renren', 'welcome_title')."$bbname!";
	$welcomemsgtxt = lang('renren', 'hello').$username.'!'.lang('renren', 'welcome_msg');
	sendpm($uid, $welcomtitle, $welcomemsgtxt, 0);
	
	
	return $uid;
}

function rr_bind($rr_uid, $dz_uid, $tag=0) {
	$data = array('rr_uid' => $rr_uid,
				  'dz_uid' => $dz_uid,
				  'tag'	   => $tag);
	$data = daddslashes($data);
	return DB::insert('renren_connect', $data);
}

function rr_make_bind($dz_uid) {
	global $_G;
	if(empty($dz_uid))
		$dz_uid = $_G['uid'];
	
	$rr_uid = rr_get_cookie('user');
	
	if(!empty($rr_uid))
		rr_bind($rr_uid, $dz_uid, 1);
}

function rr_unbind() {
	global $_G;
	$dz_uid = $_G['uid'];
	$condition = "dz_uid = $dz_uid";
	return @DB::delete('renren_connect', $condition);
}

function rr_is_bind() {
	global $_G;

	if(empty($_G['renren'])) {
		$dz_uid = $_G['uid'];
		$tag = DB::result_first("SELECT tag FROM ".DB::table('renren_connect')." WHERE dz_uid='$dz_uid' ORDER BY tag DESC");
	} else {
		$rr_uid = rr_get_rr_uid();
		$tag = DB::result_first("SELECT tag FROM ".DB::table('renren_connect')." WHERE rr_uid='$rr_uid' ORDER BY tag DESC");
	}
	if(isset($tag) && intval($tag)>0)
		return true;
	else
		return false;
}


function rr_get_bind_dz_uid($rr_uid) {
	return DB::result_first("SELECT dz_uid FROM ".DB::table('renren_connect')." WHERE rr_uid='$rr_uid' ORDER BY tag DESC");
}

function rr_get_bind_rr_uid($dz_uid) {
	return DB::result_first("SELECT dz_uid FROM ".DB::table('renren_connect')." WHERE dz_uid='$dz_uid' ORDER BY tag DESC");
}

function rr_get_cookie($key) {
	global $_G;
	loadcache('plugin');
	$api_key = $_G['cache']['plugin']['renren']['api_key'];
	return getgpc($api_key.'_'.$key,'C');
}

function rr_get_session($key) {
	global $_G;
	return $_G['renren']['session'][$key];
}

function rr_get_dz_uid() {
	global $_G;
	return $_G['renren']['dz_uid'];
}

function rr_get_rr_uid() {
	global $_G;
	return $_G['renren']['rr_uid'];
}

function rr_generate_sig($params, $secret) {
	ksort($params);
	$sig = '';
	foreach($params as $key=>$value) {
		$sig .= "$key=$value";
	}
	
	$sig .= $secret;
	
	return md5($sig);
}

?>
